#include "Dynamicarry.h"
#include <stdio.h>
#include <stdlib.h>



struct DynamicArray
{
    ElementType *array;             // 数组指针
    int capacity;                   // 数组容量
    int size;                       // 数组大小
    void (*FreePtr)(ElementType p); // 释放函数的函数指针
};

DArray *InitDArray(int capacity, void (*FreePtr)(ElementType p))
{
    DArray *a = (DArray *)malloc(sizeof(DArray) * 1);
    if (a == NULL)
    {
        printf("申请DArray失败!\n");
        return NULL;
    }
    // 初始化结构体变量
    a->FreePtr = FreePtr;
    a->capacity = capacity;
    a->size = 0;
    a->array = (ElementType *)malloc(sizeof(ElementType) * a->capacity);
    if (a->array == NULL)
    {
        printf("申请数组失败!\n");
        free(a);
        return NULL;
    }
    return a;
}

void FreeDArray(void *ptr)
{   DArray*a=(DArray*)ptr;
    if (a)
    {
        if (a->array)
        { // 释放指针不为空
            if (a->FreePtr != NULL)
            {
                for (int i = 0; i < a->size; i++)
                {
                    a->FreePtr(a->array[i]);
                }
                free(a->array);
            }
        }
        free(a);
    }
}

bool InsertTail(DArray *a, ElementType element)
{

    if (a->size >= a->capacity)
    {
        ElementType *newP = (ElementType *)realloc(a, a->capacity * 2);
        if (newP == NULL)
        {
            printf("申请空间失败!\n");
            return false;
        }
        a->capacity *= 2;
        a->array = newP;
    }
    a->array[a->size++] = element;

    return true;
}

void PrintArray(DArray *a, void (*printf)(ElementType p))
{
    for (int i = 0; i < a->size; i++)
    {
        printf(a->array[i]);
    }
}

ElementType FindElement(DArray *a, ElementType element, bool (*find)(ElementType, ElementType))
{
    for (int i = 0; i < a->size; i++)
    {
        if (find(a->array[i], element) == true)
        {
            return a->array[i];
        }
    }
    return NULL;
}

void DeleteValue(DArray *a, int element)
{
    if (element < 0 || element >= a->size)
    {
        printf("非法位置\n");
        return;
    }
    if (a->FreePtr != NULL)
    { // 释放要删除的位置的指针
        a->FreePtr(a->array[element]);
    }
    for (int i = element; i < a->size; i++)
    {
        a->array[i] = a->array[i + 1];
    }
    a->size--;
}

void DeleteByElement(DArray *a, ElementType element)
{
    for (int i = 0; i < a->size; i++)
    {
        if (a->array[i] == element)
        {
            DeleteValue(a, i);
            i--;
        }
    }
}
